package com.bpc.cs.dao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;

import com.bpc.cs.dto.FactorChoiceDTO;
import com.bpc.cs.dto.RuleDTO;
import com.bpc.cs.util.LoggerUtils;

/**
 * @author   phan_tp
 * @datetime Nov 30, 2012 : 5:19:37 PM
 */
public class RuleDAO extends BaseDAO implements IRuleDAO {

	Logger logger = LoggerUtils.getLogger();

	/**
	 * Select list factorChoice of ruleID
	 * @param int ruleID
	 * @return List<FactorChoiceDTO>
	 */
	@Override
	public List<FactorChoiceDTO> selectFactorChoiceByRuleID(int ruleID) {
		// Loadd ruleDTO
		RuleDTO ruleDTO = (RuleDTO)getSession().get(RuleDTO.class, ruleID);

		// List contains factorChoices
		List<FactorChoiceDTO> listFactorChoiceDTO = new ArrayList<FactorChoiceDTO>();
		Iterator<FactorChoiceDTO> iRuleDTO = ruleDTO.getFactorChoiceTO().iterator();

		// Add all facotr choice to list
		while (iRuleDTO.hasNext()) {
			FactorChoiceDTO factorChoiceDTO = iRuleDTO.next();
			listFactorChoiceDTO.add(factorChoiceDTO);
		}
		return listFactorChoiceDTO;
	}

	/**
	 * Insert new rule
	 * @param RuleDTO ruleDTO
	 * @return boolean TRUE : Insert successfully
	 * 				   FALSE: Insert failed
	 */
	public boolean insertRule(RuleDTO ruleDTO) {
		getSession().save(ruleDTO);
		return true;
	}

	/**
	 * Update rule
	 * @param RuleDTO ruleDTO
	 * @return boolean TRUE : Update successfully
	 * 				   FALSE: Update failed
	 */
	public boolean updateRule(RuleDTO ruleDTO) {
		getSession().update(ruleDTO);
		return true;
	}

	/**
	 * Delete rule from SCORING_RULE table
	 * @param int ruleID
	 * @return boolean TRUE : delete successfully
	 * 				   FALSE: delete failed
	 */
	public boolean deleteRule(int ruleID) {
		int numEffRow = getSession().createQuery("DELETE FROM RuleDTO WHERE ruleID = ?")
									.setParameter(0, ruleID)
									.executeUpdate();
		return numEffRow == 1;
	}

	/**
	 * Delete entire rule and factor choice
	 * @param int ruleID
	 * @return boolean TRUE : Delete successfully
	 * 				   FALSE: Delete failed
	 */
	@Override
	public boolean deleteEntireRule(int ruleID) {
		getSession().delete((RuleDTO)getSession().load(RuleDTO.class, ruleID));
		return true;
	}

	/**
	 * Check factorName is duplicated or not
	 * @param int schemeID
	 * @param int factorID
	 * @return boolean TRUE : FactorName is duplicated
	 * 				   FALSE: FactorName isn't duplicated
	 */
	public boolean isDuplicatedFactorName(final int schemeID, final int factorID) {
		String strQuery = "SELECT COUNT(*) FROM RuleDTO WHERE schemeDTO.schemeID = ? and factorDTO.factorID = ?";
		return 0 < ((Number)getSession().createQuery(strQuery)
										.setParameter(0, schemeID)
										.setParameter(1, factorID)
										.uniqueResult())
										.intValue();
	}
}
